<template>
  <!-- 表格 -->
  <my-table
    :tableData="tableData"
    :propList="propList"
    v-model:pagination="pagination"
    :tableLoading="tableLoading"
    :hasSearch="false"
    @updateTableData="refreshTable"
  >
    <template #tableAction><el-button type="success" @click="handleAdd">新增</el-button></template>
    <template #carousel="{ row }">
      <img :src="row.carousel" alt="图片" width="auto" height="60" />
    </template>
    <template #is_use="{ row }">
      {{ $utils.$filter.isUseOptionsFilter(row.is_use) }}
    </template>
    <template #action="{ row }">
      <el-button type="primary" @click="handleEdit(row._id, row.is_use)">编辑</el-button>
      <del-button @deleteHandler="deleteHandler(row._id)"></del-button>
    </template>
  </my-table>
  <!-- banner弹窗 -->
  <my-drawer :title="drawerTitle" v-model="drawer">
    <DrawerSlot
      :drawerStatus="drawerStatus"
      :editId="editId"
      v-model:is_use="is_use"
      @updateBannerData="updateBannerData"
      @closeDrawer="closeDrawer"
    ></DrawerSlot>
  </my-drawer>
</template>

<script setup>
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import DrawerSlot from './DrawerSlot.vue'
import useTable from '@/hooks/useTable'
import { getBnnerList, delBanner } from '@/api/banner'
defineOptions({ name: 'BannerIndex' })
// 定义表格属性
const propList = ref([
  { label: '图片地址', slotName: 'carousel' },
  { label: '是否现在启用', slotName: 'is_use' },
  { prop: 'date', label: '更新日期' },
  { label: '更新日期', slotName: 'action', width: '300' }
])

// 获取banner列表
const { tableData, tableLoading, pagination, refreshTable } = useTable(getBnnerList)

//定义弹窗属性
const drawer = ref(false)
const drawerTitle = computed(() => {
  return drawerStatus.value == 'update' ? '编辑轮播图' : '新增轮播图'
})
// 定义弹窗内容模板
const drawerStatus = ref('')
const editId = ref('')
const is_use = ref(false)

// 新增banner
const handleAdd = () => {
  drawer.value = true
  drawerStatus.value = 'add'
  is_use.value = false
}
// 编辑banner
const handleEdit = (id, isUse) => {
  drawer.value = true
  drawerStatus.value = 'update'
  editId.value = id
  is_use.value = isUse
}
// 删除banner
const deleteHandler = async (id) => {
  try {
    await delBanner(id)
    ElMessage({
      type: 'success',
      message: '删除成功!'
    })
    refreshTable()
  } catch (error) {
    console.log(error)
  }
}
// 更新表格数据
const updateBannerData = () => {
  if (drawerStatus.value == 'add') {
    pagination.value.pageNumber = 1
  }
  refreshTable()
  closeDrawer()
}
// 关闭弹窗
const closeDrawer = () => {
  drawer.value = false
}
</script>
